#!/user/bin/env python3
# -*- coding: utf-8 -*-
import numpy as np
from datetime import datetime

# 随机漫步
# nwalks = 5000
# nsteps = 1000
# draws = np.random.randint(0, 2, size=(nwalks, nsteps))
# steps = np.where(draws > 0, 1, -1)
# walks = steps.cumsum(1)
# print(walks)
#
# hits30 = (np.abs(walks) >= 30).any(1)
# print(hits30)
# print(hits30.sum())
#
# crossing_times = (np.abs(walks[hits30]) >= 30).argmax(1)
# print(crossing_times)
# print(crossing_times.mean())


#  利用Numpy进行股价分析
c, v = np.loadtxt('data.csv', delimiter=',', usecols=(6, 7), unpack=True)
# print(c, v)

# 计算成交量加权平均价格
vwap = np.average(c, weights=v)
print("VWAP = ", vwap)

# 算数平均价格
m = np.mean(c)
print("mean = ", m)

# 时间加权平均价格
t = np.arange(len(c))
print('twap = ', np.average(c, weights=t))

# 统计分析
c = np.loadtxt('data.csv', delimiter=',', usecols=(6,), unpack=True)
print("median = ", np.median(c))  # 中位数
sorted = np.msort(c)
# print('sorted = ', sorted)

# 股票收益率
returns = np.diff(c) / c[:-1]
print("Standard deviation = ", np.std(returns))  # 标准差

logreturns = np.diff(np.log(c))
posretindices = np.where(returns > 0)
print("Indices with positive returns", posretindices)

annual_voli = np.std(logreturns) / np.mean(logreturns)
annual_voli /= np.sqrt(1. / 252.)
print("Annual volatility", annual_voli)
print('Monthly volatility', annual_voli / np.sqrt(1. / 12.))


# 日期分析
# Monday 0
# Tuesday 1
# Wednesday 2
# Thursday 3
# Friday 4
# Saturday 5
# Sunday 6


def datestr2num(s):
    return datetime.strptime(s, "%d-%m-%Y").date().weekday()


#
#
# dates, close = np.loadtxt('data.csv', delimiter=',', usecols=(1, 6),
#                           converters={1: datestr2num}, unpack=True)
# dates, close= np.loadtxt('data.csv', delimiter=',', usecols=(1, 6), unpack=True)
# print("Dates = ", dates)
#
# averages = np.zeros(5)
# for i in range(5):
#     indices = np.where(dates == i)
#     prices = np.take(close, indices)
#     avg = np.mean(prices)
#     print("Day", i, "prices", prices, "Average", avg)
#     averages[i] = avg
